package com.mongo.operation.controller;


import com.mongo.operation.data.DataMongoObject;
import com.mongo.operation.data.DataRepository;
import com.mongo.operation.service.GridFsMongoService;
import com.mongo.operation.util.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/api/mongo")
public class ParsedDataController {

    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private DataRepository dataRepository;
    @Autowired
    private GridFsMongoService gridFsMongoService;

    private static final SimpleDateFormat DATE_FORMAT
            = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 保存用户数据
     *
     * @param dataMongoObject
     * @return
     */
    @PostMapping(value = "/data", consumes = "application/json;charset=utf8")
    public String saveData(@RequestBody DataMongoObject dataMongoObject) {
        ResultInfo resultInfo = new ResultInfo();
        log.info("开始存储原始数据,{}", dataMongoObject.getToken());
        try {
            DataMongoObject old = gridFsMongoService.getDataByFileName(dataMongoObject.getToken());
            if (old != null && StringUtils.isNotBlank(old.getId())) {
                dataMongoObject.setId(old.getId());
            } else {
                dataMongoObject.setId(null);
            }
            Date now = new Date();
            boolean isBigger = ObjectUtil.compareObjectSize(dataMongoObject, Constans.MONGO_LIMIT_SIZE);
            log.info("验证保存mongo数据大于16M结果:{}", !isBigger);
            if (isBigger) {
                dataRepository.save(dataMongoObject);
            } else {
                log.info("存储mongo数据大于16M开始存入gridFS,token:{}", dataMongoObject.getToken());
                gridFsMongoService.saveJsonToGridFS(dataMongoObject, dataMongoObject.getToken());
            }
            resultInfo.setSuccess(true);
            log.info("存储原始数据完毕,{}", dataMongoObject.getToken());

        } catch (Exception e) {
            resultInfo.setSuccess(false);
            LOGGER.error(e.getMessage(), e);
            resultInfo.setMsg(e.getMessage());
        }
        return resultInfo.toString();
    }

    /**
     * page从零开始的,这里做了处理,从1开始
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/data/all")
    public String findAll(Integer pageNum, Integer pageSize) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            if (StringUtil.isEmpty(pageNum) || pageNum < 1 || pageNum >= Consts.MAX_SIZE) {
                pageNum = Consts.DEFAULT_PAGE_NUM;
            }

            if (StringUtil.isEmpty(pageSize) || pageSize < 1 || pageSize >= Consts.MAX_SIZE) {
                pageSize = Consts.DEFAULT_PAGE_SIZE;
            }

            Page<DataMongoObject> all = dataRepository.findAll(new PageRequest(--pageNum, pageSize));
            resultInfo.setSuccess(true);
            resultInfo.setDetail(all);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return resultInfo.toString();
    }


    @GetMapping(value = "/data/token/{token}")
    public String findByToken(@PathVariable("token") String token) {
        ResultInfo resultInfo = new ResultInfo();
        try {
            DataMongoObject one = gridFsMongoService.getDataByFileName(token);
            resultInfo.setSuccess(true);
            resultInfo.setDetail(one);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            resultInfo.setMsg(e.getMessage());
            resultInfo.setSuccess(false);
        }
        return resultInfo.toString();
    }

    @GetMapping("/data/sourceName/{sourceName}")
    public String findBySourceName(String sourceName, Integer pageNum, Integer pageSize) {
        ResultInfo resultInfo = new ResultInfo();
        try {

            if (StringUtil.isEmpty(pageNum) || pageNum < 1 || pageNum >= Consts.MAX_SIZE) {
                pageNum = Consts.DEFAULT_PAGE_NUM;
            }

            if (StringUtil.isEmpty(pageSize) || pageSize < 1 || pageSize >= Consts.MAX_SIZE) {
                pageSize = Consts.DEFAULT_PAGE_SIZE;
            }

            Page<DataMongoObject> all = dataRepository.findBySourceName(sourceName, new PageRequest(--pageNum, pageSize));
            resultInfo.setSuccess(true);
            resultInfo.setDetail(all);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            resultInfo.setMsg(e.getMessage());
            resultInfo.setSuccess(false);
        }
        return resultInfo.toString();
    }
}
